package com.haohan.jingyuan.customer.service;

import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerIncomeMapper;
import com.haohan.jingyuan.customer.dao.CustomerIncomeTypeMapper;
import com.haohan.jingyuan.customer.dto.req.CreateIncomeTypeRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteIncomeTypeRequest;
import com.haohan.jingyuan.customer.dto.resp.IncomeTypeInfoResp;
import com.haohan.jingyuan.customer.dto.resp.IncomeTypeListResp;
import com.haohan.jingyuan.customer.entity.CustomerIncomeType;
import com.haohan.jingyuan.customer.helper.IncomeTypeRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户收入类型服务实现类
 *
 * @ClassName CustomerIncomeTypeService
 * @Description 客户收入类型相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 17:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerIncomeTypeService {

    /**
     * 客户收入类型Mapper
     */
    private final CustomerIncomeTypeMapper customerIncomeTypeMapper;

    /**
     * 客户收入Mapper
     */
    private final CustomerIncomeMapper customerIncomeMapper;

    /**
     * 创建收入类型
     *
     * @param request 创建收入类型请求
     * @return 收入类型信息
     */
    public IncomeTypeInfoResp createIncomeType(CreateIncomeTypeRequest request) {
        // 校验类型编码是否已存在
        CustomerIncomeType existingType = customerIncomeTypeMapper.findByType(request.getType());
        if (existingType != null) {
            throw new BusinessException(ErrorEnum.INCOME_TYPE_ALREADY_EXISTS);
        }

        // 创建收入类型记录
        CustomerIncomeType customerIncomeType = new CustomerIncomeType();
        customerIncomeType.setType(request.getType());
        customerIncomeType.setTypeName(request.getTypeName());
        customerIncomeType.setDescription(request.getDescription());
        EntityUtil.setCreateAndModifyInfo(customerIncomeType, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerIncomeTypeMapper.insert(customerIncomeType);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return IncomeTypeRespHelper.convert2IncomeTypeInfoResp(customerIncomeType);
    }

    /**
     * 查询收入类型列表
     *
     * @return 收入类型列表
     */
    public IncomeTypeListResp queryIncomeTypeList() {
        // 查询所有收入类型（按创建时间倒序）
        List<CustomerIncomeType> incomeTypeList = customerIncomeTypeMapper.selectAll();

        // 转换为响应对象
        List<IncomeTypeInfoResp> incomeTypeInfoList = new ArrayList<>();
        for (CustomerIncomeType record : incomeTypeList) {
            incomeTypeInfoList.add(IncomeTypeRespHelper.convert2IncomeTypeInfoResp(record));
        }

        IncomeTypeListResp response = new IncomeTypeListResp();
        response.setIncomeTypeList(incomeTypeInfoList);
        return response;
    }

    /**
     * 删除收入类型
     *
     * @param request 删除收入类型请求
     * @return 删除结果
     */
    public boolean deleteIncomeType(DeleteIncomeTypeRequest request) {
        // 查询收入类型是否存在
        Long id = Long.parseLong(request.getId());
        CustomerIncomeType customerIncomeType = customerIncomeTypeMapper.selectById(id);
        if (customerIncomeType == null) {
            throw new BusinessException(ErrorEnum.INCOME_TYPE_NOT_FOUND);
        }

        // 校验此收入类型是否被客户收入记录使用
        int usageCount = customerIncomeMapper.countByIncomeType(customerIncomeType.getType());
        if (usageCount > 0) {
            throw new BusinessException(ErrorEnum.INCOME_TYPE_IN_USE);
        }

        // 逻辑删除
        customerIncomeType.setIsDeleted("Y");
        EntityUtil.setModifyInfo(customerIncomeType, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerIncomeTypeMapper.updateById(customerIncomeType);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return true;
    }
}
